package com.avic.modules.mapping.service.impl;

import com.avic.common.service.impl.BaseServiceImpl;
import com.avic.common.utils.QueryHelpPlus;
import com.avic.enums.AlarmEnum;
import com.avic.modules.mapping.domain.DataMapping;
import com.avic.modules.mapping.service.DataMappingService;
import com.avic.modules.mapping.service.dto.DataMappingQueryCriteria;
import com.avic.modules.mapping.service.mapper.DataMappingMapper;
import com.avic.modules.realtime.constants.RedisOPCItem;
import com.avic.modules.record.service.AlarmInformationService;
import com.avic.modules.system.domain.DictDetail;
import com.avic.modules.system.service.mapper.DictDetailMapper;
import com.avic.utils.RedisUtils;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangzikang 设备点位表
 * @date 2022-08-14
 */
@Service(value = "dataMappingService")
@AllArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
@Lazy
public class DataMappingServiceImpl extends BaseServiceImpl
        <DataMappingMapper, DataMapping> implements DataMappingService {

    private final RedisUtils redisUtils;
    private final DataMappingMapper dataMappingMapper;
    private final DictDetailMapper dictDetailMapper;
    private final AlarmInformationService alarmInformationService;

    /**
     * 查询某个设备下所有点位
     *
     * @param equipId
     * @return
     */
    @Override
    public List<DataMapping> selectEquipMapping(String equipId,Long categoryId) {
        DataMappingQueryCriteria criteria = new DataMappingQueryCriteria();
        criteria.setEquipId(equipId);
        List<DataMapping> list = baseMapper.selectList(QueryHelpPlus.getPredicate(DataMapping.class, criteria));
        takeDataMappingWithChinese(list,equipId);
        return list;
    }

    private void takeDataMappingWithChinese(List<DataMapping> list,String equipId) {
        if (list.size() > 0) { // 判断长度是否大于0
            list.stream().forEach(ele -> {
                Object valueOfPoint = getValueOfPoint(ele.getDataAddr(), RedisOPCItem.ITEM_VALUE);
                if (valueOfPoint == null) {
                    ele.setValue("");
                } else {
                    String name = valueOfPoint.toString();
                    if (name.equalsIgnoreCase("true")) {
                        name = "1";
                    } else if (name.equalsIgnoreCase("false")) {
                        name = "0";
                    }
                    if (ele.getRecordType() != null) {
                        long recordCate = ele.getRecordCate();
                        if (recordCate == AlarmEnum.TWENTY_THREE.getCode() || recordCate == AlarmEnum.TWENTY_FOUR.getCode() || recordCate == AlarmEnum.TWENTY_Five.getCode()) {
                            DictDetail dictDetail = dictDetailMapper.selectDictDetailLabel(ele.getRecordCate(), "1");
                            ele.setChineseMeaning(dictDetail != null ? dictDetail.getLabel() : "");
                        } else {
                            DictDetail dictDetail = dictDetailMapper.selectDictDetailLabel(ele.getRecordCate(), name);
                            ele.setChineseMeaning(dictDetail != null ? dictDetail.getLabel() : "");
                        }

                        ele.setValue(name);
                    }
                }
                ele.setCompany(ele.getCompany() == null ? "" : ele.getCompany());

            });
            alarmInformationService.addAlarmInformation(list,equipId);
        }
    }

    /**
     * 查询点位数据
     * @param criteria
     * @return
     */
    @Override
    public Map<String, Object> selectDataMapping(DataMappingQueryCriteria criteria) {
        List<DataMapping> list = dataMappingMapper.selectDataMapping(criteria.getEquipId());
        List<DataMapping> listAll = new ArrayList<>();
        Integer sun = 0;
        Integer total = 0;
        for(DataMapping mapping:list){
            if(mapping.getIsDel()==0){
                sun++;
            }
            if(mapping.getRecordCate()!=null){
                long recordCate = mapping.getRecordCate();
                if(recordCate != AlarmEnum.TWENTY_TWO.getCode() && recordCate != AlarmEnum.TWENTY_ONE.getCode() &&
                        recordCate != AlarmEnum.FOURTEEN.getCode() && recordCate != AlarmEnum.FIFTEEN.getCode()){
                    listAll.add(mapping);
                }else{
                    total++;
                }
            }else {
                listAll.add(mapping);
            }
        }
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content",listAll);
        map.put("collection", list.size()-total);
        map.put("monitor", sun-total);

        return map;
    }

    /**
     * 修改点位信息
     * @param criteria
     */
    @Override
    public void eatDataMapping(DataMapping criteria) {
        dataMappingMapper.updateById(criteria);
    }

    @Override
    public List<DataMapping> selectRunningDataMapping(DataMappingQueryCriteria criteria) {
        List<DataMapping> list = baseMapper.selectList(QueryHelpPlus.getPredicate(DataMapping.class, criteria));
        for(DataMapping ele:list){
            Object valueOfPoint = getValueOfPoint(ele.getDataAddr(), RedisOPCItem.ITEM_VALUE);
            if (valueOfPoint == null) {
                ele.setValue("");
            } else {
                String name = valueOfPoint.toString();
                if (name.equalsIgnoreCase("true")) {
                    name = "1";
                } else if (name.equalsIgnoreCase("false")) {
                    name = "0";
                }
                ele.setValue(name);
            }
        }
        return list;
    }

    /**
     * 根据点位 tagName 获取对应的 hash 项
     *
     * @param tagName 标签
     * @param item    哈希项
     */
    public Object getValueOfPoint(String tagName, String item) {
        if (redisUtils.hHasKey(tagName, item)) {
            return redisUtils.hget(tagName, item);
        }
        return null;
    }

}
